package com.klun.lockTest.deadLock;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

public class DeadLockTest {

    public static void main(String[] args) {
        
        DLDemo dlDemo = new DLDemo();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    dlDemo.take();
                }
            }
        },"deadLockTest1");

        // Thread t2 = new Thread(() -> dlDemo.put(new Random().nextInt(1000)));

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    dlDemo.put(new Random().nextInt(1000));
                }
            }
        },"deadLockTest3");

        t1.start();
        t3.start();

    }

    static class DLDemo{
        final List<Integer> list =  new LinkedList();
        private ReentrantLock takeLock = new ReentrantLock();
        private ReentrantLock putLock = new ReentrantLock();

        public void take(){
            try{
                takeLock.lock();
                if(null != list){
                    System.out.println("take获取putLock");
                    putLock.lock();
                }
                // 获取之后删除
                Integer o = list.get(0);
                System.out.println("take获取的值"+o);
                list.remove(0);
            }finally {
                takeLock.unlock();
                putLock.unlock();
            }

        }
        public void put(Integer num){
            try{
                putLock.lock();
                if(null != list){
                    System.out.println("put获取takeLock");
                    System.out.println("put的值"+num);
                    takeLock.lock();
                }
                list.add(num);
            }finally {
                putLock.unlock();
                takeLock.unlock();
            }
        }

    }

}
